﻿using Manina.Windows.Forms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LicenseAutoDetection
{
    /*
     * 파일 삭제를 별도의 쓰레드로 구현
     * 많은 양의 파일을 삭제 시 UI가 먹통이 되고, 삭제 중지를 시킬 수 없음
     */
    public class DeleteTask : IDisposable
    {
        public Task task;
        CancellationTokenSource tokenSource;
        MainForm mainForm;
        ProgressReporter ui = new ProgressReporter();

        public Boolean IsCompleted
        {
            get
            {
                return task == null || task.IsCompleted;
            }
        }

        public DeleteTask(MainForm main)
        {
            mainForm = main;
        }

        public void Start(string path)
        {
            Cancel(); // 기존 쓰레드가 동작중 일 경우 cancel 시킴
            tokenSource = new CancellationTokenSource();
            task = Task.Factory.StartNew(() => Delete(path, tokenSource.Token), tokenSource.Token);
        }

        public void Cancel()
        {
            if (task != null && !task.IsCompleted)
            {
                tokenSource.Cancel();
            }
        }

        /*
         * 파일 삭제
         */
        private void Delete(string path, CancellationToken ct)
        {
            double step = 100.0 / mainForm.ImageListView.SelectedItems.Count;
            double progress = 0;
            mainForm.transData.DeletedClear();
            ui.Update(() => {
                mainForm.UpdateMenuStateByStart(true);
            });

            foreach (ImageListViewItem item in mainForm.ImageListView.SelectedItems)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                progress += step;
                ui.Update(() => mainForm.UpdateStatusStrip(item.FileName, "삭제중", (int)progress));
                
                try
                {
                    File.Delete(@item.FileName);
                    mainForm.transData.DeletedAdd = item.FileName;
                    ui.Update(() => mainForm.RemoveImageListViewItem(item));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "삭제 실패", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            ui.Update(() =>
            {
                mainForm.UpdateStatusStrip(path, ct.IsCancellationRequested ? "삭제취소" : "삭제완료", 0);
                mainForm.UpdateMenuStateByStart(false);

                if (ct.IsCancellationRequested)
                {
                    MessageBox.Show("삭제를 취소하였습니다.", "삭제 취소", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    mainForm.transData.TransmissionDel();
                    MessageBox.Show("삭제를 완료하였습니다.", "삭제 완료", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            });
            mainForm.transData.DeletedClear();
        }

        #region IDisposable 구현
        private bool disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing && tokenSource != null)
                {
                    if (tokenSource != null) tokenSource.Dispose();
                }

                disposed = true;
            }
        }

        ~DeleteTask()
        {
            Dispose(false);
        }
        #endregion
    }
}
